var CommissionPayModule = function () {
    var editable = function () {

        return {
            init: function () {
                var oTable = $('#modelEditable').dataTable({
                	"autoWidth":true,
                	"lengthMenu": [
                                   [10, 15, 20, 50],
                                   [10, 15, 20, 50]
                               ],
                    "displayLength": 10,
                    "scrollX":true,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                        "infoEmpty" : "记录数为0",
                     },
                     "columnDefs": [
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [0]
            						},
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [1]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [2]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [3]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [4]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [5]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [6]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [7]
            						},
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [8]
            						},
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [9]
            						},
                                ],
                     "columns": [
                                { "data": "" },
                                { "data": "payTime" },
                                { "data": "orderId" },
                                { "data": "orderAmount"},
                                { "data": null },
                                { "data": null },
                                { "data": null},
                                { "data": "cPayName"},
                                { "data": "cPayTime"},
                                ],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/commissionPay/queryEmp",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.id;
                	   $('td:eq(2)', nRow).html('<a href="orders/detail/'+aData.orderId+'">'+aData.orderId+'</a>');
//                	   $('td:eq(2)', nRow).html("<center>"+aData.employeeName+"<br>工号："+aData.employeeNo+"</center>");
//                	   $('td:eq(3)', nRow).html('<a href="product/detail/'+aData.productId+'">'+aData.productBriefName+'</a>');
//                	   
                	   $('td:eq(3)', nRow).html(formatCurrency(aData.orderAmount)+"&nbsp;元");
//                	   $('td:eq(6)', nRow).html(formatCurrency(aData.payAmount)+"&nbsp;元");
//                	   
                	   if(aData.dividendRate == undefined||aData.dividendRate==0||aData.dividendRate==null){
                		   $('td:eq(4)', nRow).html("佣金："+toPercent(aData.commissionRate));
                		   $('td:eq(5)', nRow).html("佣金："+formatCurrency(aData.orderAmount*aData.commissionRate)+"&nbsp;元");
                	   }else if(aData.commissionRate == undefined||aData.commissionRate==0||aData.commissionRate==null){
                		   $('td:eq(4)', nRow).html("提成："+toPercent(aData.dividendRate));
                		   $('td:eq(5)', nRow).html("提成："+formatCurrency(aData.orderAmount*aData.dividendRate)+"&nbsp;元");
                	   }else{
                		   $('td:eq(4)', nRow).html("提成："+toPercent(aData.dividendRate)+"&nbsp;"+"佣金："+toPercent(aData.commissionRate));
                		   $('td:eq(5)', nRow).html("提成："+formatCurrency(aData.orderAmount*aData.dividendRate)+"&nbsp;元"+"&nbsp;"+"佣金："+formatCurrency(aData.orderAmount*aData.commissionRate)+"&nbsp;元");
                	   }
                	   
//                	   var auditState;
//                	   if(aData.state == 0){
//                		   auditState = "未审核";
//                	   }else if(aData.state == 1){
//                		   auditState = "已审核";
//                	   }else if(aData.state == 2){
//                		   auditState = "已结算";
//                	   }else{
//                		   auditState = "未审核";
//                	   }
                	   
                	   var auditState;
                	   var opera;
                	   if(aData.state == 2){
                		   auditState = "已结算";
                		   opera = "<center>--</center>"
                	   }else{
                		   auditState = "未结算";
                		   opera = '<a class="settle fa fa-credit-card" title="结算" href="javascript:;"></a>';
                		   $('td:eq(0)', nRow).html('<input class="deviceId" type="checkbox" value="">');
                	   }
                	   
                	   $('td:eq(6)', nRow).html(auditState);
                	   $('td:eq(9)', nRow).html(opera);
                       return nRow;
                   },
                   "fnInitComplete": function() {
                	   $('input:checkbox').each(function(index,domEle){
                       	if(index != 0){
                       		$(domEle).bind("click", (function (e) {
                       			var flag = $('input:checkbox:eq(0)')[0].checked == true ? 1 : 0;
                       			if(1 == flag){
                       				$('input:checkbox:eq(0)')[0].checked = false;
                       			}
                       		}));
                       	}
                       });
					},
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                   var json = "";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"start":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
	                   var form = $("form#queryForm").serializeJSON();
                   	   var js = form.replace('}', ',');
                   	   json = js + json + "}";
                       $.ajax({
                       	"contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ajaxSource,
                           "data" : json,
                           "success" : fnCallback
                       });
                   },
                });
                //结算
                $('#modelEditable').on("click", "a.settle", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    
                    $("#settleBody").empty();// clean
                    var msg ={};
                    msg.content = nRow.children[5].innerText;
                    msg.id = id;
                    msg.employeeName = $('#employeeName').val();
                	var tmpl = $("#settleTemplate").tmpl(msg).appendTo("#settleBody");
                	var modal = $('#settleModal').modal('show');
                	modal.on("hidden.bs.modal",function(e){
                		$(this).removeData();
                	});
                	$("#settleConfirm").unbind("click").click(function(){
                		var json = $("form#settleForm").serializeJSON();
	                	var modal = $('#settleModal');
                        $.ajax({
                        	  "contentType":"application/json; charset=UTF-8",
                        	  type:"post",
                            url: ctx + "/commissionPay/settle",
                            data: json,
                            dataType:"json",
                            success: function(msg){
                            	if (msg.code == 1) {
                            		bootbox.alert("结算成功！");
                            		oTable.fnDraw(false);
                            		modal.modal('hide');
                            	} else {
                            		bootbox.alert(msg.message);
                            	}
                            },
                            error: function (msg) {
                            	bootbox.alert(msg.message);
                            }
                        });
                        });
                }));
//                // 明细
//                $('#modelEditable').on("click", "a.detail", (function (e) {
//                    e.preventDefault();
//
//                    var nRow = $(this).parents('tr')[0];
//                    var id = nRow.children[0].id;
//                	
//                    window.location.href = "commissionPay/detail/"+id;
//                }));
                
                $('#queryBtn').click(function(){
                	oTable.fnClearTable();
                });
                
                $('#saveSettle').click(function(){
                	var list = new Array();
                	$('input:checkbox').each(function(index,domEle){
                		if(0 == index){
                			return true;// false时相当于break, 如果return true 就相当于continure。
                		}
                		var selectedId= $(this).parent('td').attr("id");
                		if(true == domEle.checked){
                			list.push('"'+selectedId+'"');
                		}
                	});
                	if(list.length == 0){
                		bootbox.alert("请选择需结算的条目");
                		return;
                	}else{
                		bootbox.confirm({  
                	        buttons: {  
                	            confirm: {  
                	                label: '确认',  
                	                className: 'btn-primary'  
                	            },  
                	            cancel: {  
                	                label: '取消',  
                	                className: 'btn-white'  
                	            }  
                	        },  
                	        message: '确认结算所选的佣金条目？',  
                	        callback: function(result) {  
                	            if(result) {  
                	            	var json = '{"commissionHistoryIdList":['+list+']}';
                                	$.ajax({
                                    	type:"post",
                                        contentType:"application/json; charset=UTF-8",
                                        url: ctx + "/commissionPay/settleAll",
                                        data:json,
                                        dataType:"json",
                                        success: function(msg){
                                        	if(0 == msg.code){
                                        		bootbox.alert(msg.message);
                                        		return;
                                        	}
//                                        	var modal = $('#related_pos').modal('hide');
                                        	//$("#basic_modal").modal('show');
                                        	bootbox.alert("结算成功！");
                                        	oTable.fnDraw(false);
                                        },
                                        error: function (msg) {
                                            bootbox.alert(msg.message);
                                        }
                                    });
                	            } else {  
                	            }  
                	        },  
                	        title: "温馨提示",  
                	        });  
                	}
                	
//                	var orgId = $('#orgId').val();
//                	var endTime = $('#endTime').val();
                	
                });
                
                $('#allSelected').click(function(){
                	var flag = $('input:checkbox:eq(0)')[0].checked == true ? 1 : 0;
                	if(1 == flag){
                		$('input:checkbox').each(function(index,domEle){
                			domEle.checked = true;
//                    		$(this).attr("checked",'checked');
                    	});
                	}else{
                		$('input:checkbox').each(function(index,domEle){
                			domEle.checked = false;
//                    		$(this).attr("checked",false);
                    	});
                	}
                });
                
               /* $('#addBtn').click(function(){
                	window.location.href = "product/add";
                });*/
            }

        };

    }();
    
    return {
        init: function () {
        	editable.init();
        }
    };
}();